package com.xxg.renrenproduct.dao;

import com.mongodb.client.MongoCollection;
import com.xxg.renrencommon.domain.bean.CarryProductInfo;
import com.xxg.renrenproduct.dao.bean.UploadGoodsInfo;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * 类说明
 *
 * @author szj
 * @date 2021/12/29
 */
@Repository
public class UploadGoodsInfoDao {
    private final MongoTemplate mongoTemplate;

    public UploadGoodsInfoDao(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
        createCollection();
    }

    /**
     * 创建collection
     */
    private void createCollection() {
        String collectionName = "uploadGoodsInfo";
        MongoCollection<Document> collection;
        if (!mongoTemplate.getCollectionNames().contains(collectionName)) {
            collection = mongoTemplate.createCollection(UploadGoodsInfo.class);
        }
    }

    public void insert(UploadGoodsInfo uploadGoodsInfo) {
        uploadGoodsInfo.setCreateTime(new Date());
        mongoTemplate.insert(uploadGoodsInfo);
    }

    public UploadGoodsInfo findById(String batch) {
        Query query = new Query(where("_id").is(batch));
        return mongoTemplate.findOne(query, UploadGoodsInfo.class);
    }

    public void save(UploadGoodsInfo info) {
        mongoTemplate.save(info);
    }

    public List<UploadGoodsInfo> findList(String id, Date createTimeStart, Date createTimeEnd, Integer pageNo, Integer pageSize) {
        Query query = createListQuery(id, createTimeStart, createTimeEnd);
        query.skip((pageNo - 1) * pageSize);
        query.limit(pageSize);
        return mongoTemplate.find(query, UploadGoodsInfo.class);
    }

    private Query createListQuery(String id, Date createTimeStart, Date createTimeEnd) {
        Query query = new Query();
        if (id != null && id.trim().length() > 0) {
            query.addCriteria(where("_id").is(id));
        }
        if (createTimeStart != null && createTimeEnd != null) {
            query.addCriteria(where("createTime").gte(createTimeStart).lte(createTimeEnd));
        }else if (createTimeStart != null) {
            query.addCriteria(where("createTime").gte(createTimeStart));
        }else if (createTimeEnd != null) {
            query.addCriteria(where("createTime").lte(createTimeEnd));
        }
        return query;
    }

    public long countList(String id, Date createTimeStart, Date createTimeEnd) {
        Query query = createListQuery(id, createTimeStart, createTimeEnd);
        return mongoTemplate.count(query, UploadGoodsInfo.class);
    }
}
